package flashcardtest;

import java.util.*; // for ArrayList

public class FlashCardHand implements java.io.Serializable {
	private ArrayList<FlashCard> hand;
	private FlashCardSet set;
	private int cardsInHand;
	private int theOne;
	private Random random;	// for generating random integers
	private int testKey;

	
	public FlashCardHand(FlashCardSet set) {
		this.set = set;
		this.cardsInHand = 3;
		this.random = new Random();
		this.hand = new ArrayList<FlashCard>();
		this.theOne = 0;
		this.testKey = random.nextInt(2) + 1; // 1 or 2
		this.draw();
	}
	public String getTitle() {return this.set.getTitle();}
	public void draw() {
		// clear hand and get cards from set
		this.hand.clear();

		// deal with a set that is not big enough
		if (set.size() < 3) {
			return;
		}
		
		while (this.hand.size() < 3) {
			// get a card
			FlashCard temp = this.set.drawCard();
			// determine whether it is already in the hand
			boolean duplicate = false;
			Iterator<FlashCard> itr = this.hand.iterator();
			while (itr.hasNext()){
				FlashCard temp2 = itr.next();
				if (temp.getKey1().equals(temp2.getKey1())) {
					duplicate = true;
				}
			}
			if (!duplicate) {this.hand.add(temp);}
		}
		// randomly choose one to be the test word
		this.theOne = random.nextInt(this.hand.size());
		
		// randomly decide which key to test by
		this.testKey = random.nextInt(2) + 1; // 1 or 2
	}
	public int getSize() {return hand.size();}
	public String getTestKey() {
		if (hand.size() < 3) {return "";}
		if (this.testKey == 1)
			return this.hand.get(theOne).getKey1();
		else
			return this.hand.get(theOne).getKey2();
	}
	public String getTestAnswer() {
		if (hand.size() < 3) {return "";}
		if (this.testKey == 1)
			return this.hand.get(theOne).getKey2();
		else
			return this.hand.get(theOne).getKey1();
		
	}
	public String getCardKey(int i) {
		if (hand.size() < 3) {return "";}
		// clean input. Forces i into acceptable bounds. 
		if (i < 0) {i = 0;}
		else if (i >= cardsInHand) {i = cardsInHand - 1;}
		if (this.testKey == 1)
			return this.hand.get(i).getKey2();
		else
			return this.hand.get(i).getKey1();
	}
	public boolean isCorrect(String attempt) {
		// return false if hand is empty
		if (hand.size() < 3) {return false;}
		String correct;
		if (this.testKey == 1) {
			correct = this.hand.get(this.theOne).getKey2();
		}
		else {
			correct = this.hand.get(this.theOne).getKey1(); 
		}
		return correct.equals(attempt);
		
	}

}